package com.fengxu.gamescript.ui.setting

import android.animation.ValueAnimator
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.fengxu.gamescript.R
import com.fengxu.gamescript.boot.KeySetBoot
import com.fengxu.gamescript.data.KeyConf
import com.fengxu.gamescript.data.other.KeyConfData
import com.fengxu.gamescript.ui.base.BaseActivity
import com.fengxu.gamescript.util.CommonUtils
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import com.xuexiang.xui.widget.statelayout.StatefulLayout
import com.xuexiang.xui.widget.textview.supertextview.SuperTextView
import com.xuexiang.xui.widget.toast.XToast
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.joda.time.DateTime
import kotlin.properties.Delegates

/**
 * 通用键位配置类
 */
class KeyConfActivity : BaseActivity() {

    // 状态布局
    private val stateLayout:StatefulLayout by lazy {
        findViewById(R.id.key_conf_stateLayout)
    }

    // 添加键位配置组件
    private val addConfView:View by lazy {
        findViewById(R.id.key_conf_add)
    }

    // 键位配置列表控件
    private val keyConfRecyclerView:RecyclerView by lazy {
        findViewById(R.id.key_conf_recyclerView)
    }

    // 键位配置项
    private var keyConf:KeyConf by Delegates.notNull()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_key_conf)
        onNewIntent(intent)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        keyConf = KeyConf.readKeyConf(this)
        initView()
    }

    private fun initView() {
        findViewById<View>(R.id.actionbar_back).onClick { finish() }
        findViewById<TextView>(R.id.actionbar_title).text = "键位配置"
        flowEnterAnim()
        // 为空就显示空状态
        if(keyConf.keyConfDataList.isEmpty()){
            stateLayout.showEmpty("请点击右下角增加配置项!")
        }else{
            stateLayout.showContent()
        }
        // 初始化配置列表
        keyConfRecyclerView.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
        keyConfRecyclerView.adapter = KeyConfViewAdapter()
        // 增加配置项
        addConfView.onClick { addKeyConf() }
    }

    /**
     * 增加配置项
     */
    private fun addKeyConf() {
        if(KeySetBoot.hasRunning){
            CommonUtils.toastDialog(this,content = "您已经开始了一个键位引导，不可重复设置!")
            return
        }
        val dialogView = KeySetDialogView(this)
        MaterialDialog.Builder(this)
            .title("增加配置")
            .cancelable(false)
            .customView(dialogView,false)
            .positiveText("确定")
            .autoDismiss(false)
            .onPositive { dialog, which ->
                if(!dialogView.validate()){
                    XToast.warning(this,"您还有配置项未完成!").show()
                    return@onPositive
                }
                if(keyConf.keyConfDataList.any { it.name == dialogView.keySetName }){
                    XToast.warning(this,"键位名重复，请修改后重试!").show()
                    return@onPositive
                }
                val keyConfData = dialogView.getKeyConfDataIfComplete()
                stateLayout.showContent()
                keyConf.keyConfDataList.add(keyConfData)
                keyConfRecyclerView.adapter?.notifyDataSetChanged()
                dialog.dismiss()
            }
            .negativeText("取消")
            .onNegative { dialog, which -> dialog.dismiss() }
            .show()
    }

    /**
     * 设置添加配置悬浮窗进入动画
     */
    private fun flowEnterAnim() {
        val lp = addConfView.layoutParams
        var valueAnimator = ValueAnimator.ofInt(0, lp.height)
        valueAnimator.duration = 500
        valueAnimator.addUpdateListener {
            lp.width = it.animatedValue as Int
            lp.height = it.animatedValue as Int
            addConfView.layoutParams = lp
            addConfView.requestLayout()
        }
        valueAnimator.start()
    }

    /**
     * 更新配置项
     */
    fun updateConf(index: Int){
        val dialogView = KeySetDialogView(this)
        MaterialDialog.Builder(this)
            .title("修改配置")
            .cancelable(false)
            .customView(dialogView,false)
            .positiveText("确定")
            .autoDismiss(false)
            .showListener { dialogView.initFromKeyConfData(keyConf.keyConfDataList[index])}
            .onPositive { dialog, which ->
                if(!dialogView.validate()){
                    XToast.warning(this,"您还有配置项未完成!").show()
                    return@onPositive
                }
                // 判断配置名是否更当前位置以外的其他配置名冲突
                var isConflict = false
                for (i in 0 until keyConf.keyConfDataList.size){
                    if(index != i && keyConf.keyConfDataList[i].name == dialogView.keySetName){
                        isConflict = true
                        break
                    }
                }
                if(isConflict){
                    XToast.warning(this,"配置名冲突，请修改后重试!").show()
                    return@onPositive
                }
                val keyConfData = dialogView.getKeyConfDataIfComplete()
                stateLayout.showContent()
                keyConf.keyConfDataList[index] = keyConfData
                keyConfRecyclerView.adapter?.notifyDataSetChanged()
                dialog.dismiss()
            }
            .negativeText("取消")
            .onNegative { dialog, which -> dialog.dismiss() }
            .show()
    }

    /**
     * 删除配置项
     */
    fun deleteConf(index:Int){
        val keyConfData = keyConf.keyConfDataList[index]
        CommonUtils.toastDialog(this@KeyConfActivity,title = "警告",content = "您确定要删除该项配置吗?",
            onPositive = {
                keyConf.keyConfDataList.removeAt(index)
                // 如果删除的配置是当前正激活的配置时，设置激活配置为null
                if(keyConf.activeKeyConfData.name == keyConfData.name){
                    keyConf.activeKeyConfData = null
                }
                keyConfRecyclerView.adapter?.notifyDataSetChanged()
                if(keyConf.keyConfDataList.isEmpty()){
                    stateLayout.showEmpty("请点击右下角增加配置项!")
                }
            })
    }

    override fun onDestroy() {
        KeyConf.saveConf(this)
        super.onDestroy()
    }

    /**
     * 键位布局View包装类
     */
    private class ViewHolder(v:View) : RecyclerView.ViewHolder(v){

        // 配置名称组件
        val confNameView:TextView by lazy { v.findViewById(R.id.list_keyconf_name) }

        // 配置时间组件
        val confTimeView:TextView by lazy { v.findViewById(R.id.list_keyconf_time) }

        // 配置矩阵组件，例如 3x7
        val confRectView:SuperTextView by lazy { v.findViewById(R.id.list_keyconf_rect)  }

        // 配置音是否连续组件
        val confSeriesView:SuperTextView by lazy { v.findViewById(R.id.list_keyconf_series)  }

        // 配置高音是否降调组件
        val confHighView:SuperTextView by lazy { v.findViewById(R.id.list_keyconf_highVolume)  }

        //应用配置组件
        val confUseView:TextView by lazy { v.findViewById(R.id.list_keyconf_use) }

        // 配置更新组件
        val confUpdateView:TextView by lazy { v.findViewById(R.id.list_keyconf_update) }

        // 配置删除组件
        val confDeleteView:TextView by lazy { v.findViewById(R.id.list_keyconf_delete) }
    }


    /**
     * 键位组件适配器
     */
    private inner class KeyConfViewAdapter : RecyclerView.Adapter<ViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(this@KeyConfActivity)
                .inflate(R.layout.list_key_conf, parent,false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val keyConfData = keyConf.keyConfDataList[position]
            holder.run {
                confNameView.text = keyConfData.name
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                    confNameView.tooltipText = keyConfData.name
                }
                confRectView.centerTextView.text = "${keyConfData.row} x ${keyConfData.column}"
                confSeriesView.centerTextView.text = if(keyConfData.isSeries){"连续"}else{"不连续"}
                confHighView.centerTextView.text = if(keyConfData.isAbateHighVolume){"高音降调"}else{"高音不点击"}
                confTimeView.text = DateTime(keyConfData.createTime).toString("yyyy-MM-dd")
                if(keyConf.activeKeyConfData != null && keyConfData.name == keyConf.activeKeyConfData.name){
                    // 是激活的
                    itemView.setBackgroundResource(R.drawable.list_keyconf_border_select)
                }else{
                    itemView.setBackgroundResource(R.drawable.list_keyconf_border)
                }
                // 激活配置事件
                confUseView.onClick {
                    keyConf.activeConf(keyConfData.name)
                    notifyDataSetChanged()
                }
                // 删除配置
                confDeleteView.onClick {
                    deleteConf(position)
                }
                // 更新配置
                confUpdateView.onClick {
                    updateConf(position)
                }
            }
        }

        override fun getItemCount(): Int {
            return keyConf.keyConfDataList.size
        }

    }
}